package ru.maxmatveev.dyndao.impl.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.Session;

/**
 * Provides thread-local Hibernate Session.
 * @author Max Matveev
 *         Date: Dec 20, 2008
 *         Time: 7:41:44 PM
 */
public class ThreadLocalSessionFactory {
    private static SessionFactory sessionFactory;
    private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

    /**
     * Set hibernate session factory implementation.
     * @param sessionFactory implementation to set.
     */
    public static void setSessionFactory(SessionFactory sessionFactory) {
        ThreadLocalSessionFactory.sessionFactory = sessionFactory;
    }

    /**
     * Get Session for this thread.
     * @return session object.
     */
    public static Session getSession() {
        if (sessionFactory == null) {
            throw new IllegalStateException("SessionFactory is not set");
        }
        Session session = threadLocal.get();
        if (session == null) {
            session = sessionFactory.openSession();
            threadLocal.set(session);
        }
        return session;
    }

    /**
     * Close hibernate session for this thread.
     */
    public static void close() {
        Session session = threadLocal.get();
        if (session == null) {
            throw new IllegalStateException("Session is not opened");
        }
        if (session != null) {
            session.close();
            threadLocal.set(null);
        }
    }
}
